import { defineStore } from 'pinia'
import axiosInstance from '../utils/axiosInstance'
import { useUserStore } from './user'

export const useWalletStore = defineStore('wallet', {
  state: () => ({
    balance: 0,
    loading: false,
    error: null as string | null,
  }),
  
  actions: {
    // 获取用户余额
    async fetchBalance() {
      const userStore = useUserStore()
      if (!userStore.isLoggedIn) {
        this.error = '用户未登录'
        return false
      }
      
      this.loading = true
      this.error = null
      
      try {
        const response = await axiosInstance.get('/users/profile')
        if (response.data && response.data.balance !== undefined) {
          this.balance = response.data.balance
          
          // 同步更新用户信息中的余额
          if (userStore.user) {
            userStore.user.balance = response.data.balance
          }
          
          return true
        } else {
          this.error = '获取余额失败'
          return false
        }
      } catch (error: any) {
        console.error('获取余额失败:', error)
        this.error = error.response?.data?.message || '获取余额失败'
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 充值
    async recharge(amount: number) {
      const userStore = useUserStore()
      if (!userStore.isLoggedIn) {
        this.error = '用户未登录'
        return false
      }
      
      if (amount <= 0) {
        this.error = '充值金额必须大于0'
        return false
      }
      
      this.loading = true
      this.error = null
      
      try {
        const response = await axiosInstance.post('/users/balance/recharge', { amount })
        if (response.data && response.data.user && response.data.user.balance !== undefined) {
          this.balance = response.data.user.balance
          
          // 同步更新用户信息中的余额
          if (userStore.user) {
            userStore.user.balance = response.data.user.balance
          }
          
          return true
        } else {
          this.error = '充值失败'
          return false
        }
      } catch (error: any) {
        console.error('充值失败:', error)
        this.error = error.response?.data?.message || '充值失败'
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 更新余额（用于支付后更新）
    updateBalance(newBalance: number) {
      this.balance = newBalance
      
      // 同步更新用户信息中的余额
      const userStore = useUserStore()
      if (userStore.user) {
        userStore.user.balance = newBalance
      }
    },
    
    // 减少余额（用于支付后直接减少，无需等待后端返回）
    decreaseBalance(amount: number) {
      this.balance -= amount
      
      // 同步更新用户信息中的余额
      const userStore = useUserStore()
      if (userStore.user && userStore.user.balance !== undefined) {
        userStore.user.balance -= amount
      }
    }
  }
})
